import 'package:flutter/material.dart';

class RowAutoSizeText extends StatefulWidget {
  const RowAutoSizeText({
    super.key,
    required this.leading,
    required this.trailing,
    required this.center,
    required this.centerWidth,
    this.textStyle = const TextStyle(overflow: TextOverflow.ellipsis),
  });

  /// 头部的文本
  final String leading;

  /// 尾部的文本
  final String trailing;

  /// 中间的 icon
  final Widget center;

  /// 中间区域宽度 包含间距
  final double centerWidth;

  final TextStyle textStyle;

  @override
  State<RowAutoSizeText> createState() => _RowAutoSizeTextState();
}

class _RowAutoSizeTextState extends State<RowAutoSizeText> {
  double width = 0;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getWidth();
    });
  }

  bool isAllExpanded = false;
  bool leadingExpanded = false;
  bool trailingExpanded = false;

  @override
  void didUpdateWidget(covariant RowAutoSizeText oldWidget) {
    super.didUpdateWidget(oldWidget);
    // getWidth();
  }

  void getWidth() {
    width = MediaQuery.of(context).size.width;
    final maxWidth = width - widget.centerWidth;
    final leadingWidth = calculateTextWidth(widget.leading, maxWidth);
    final trailingWidth = calculateTextWidth(widget.trailing, maxWidth);
    if (leadingWidth > maxWidth / 2) {
      leadingExpanded = true;
    }
    if (trailingWidth > maxWidth / 2) {
      trailingExpanded = true;
    }
    if (leadingExpanded && trailingExpanded) {
      isAllExpanded = true;
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    Widget current = SizedBox();
    if (width == 0) return current;
    final leadingWidget = Text(widget.leading, style: widget.textStyle, maxLines: 1);
    final trailingWidget = Text(widget.trailing, style: widget.textStyle, maxLines: 1);
    if (isAllExpanded) {
      current = Row(children: [Expanded(child: leadingWidget), widget.center, Expanded(child: trailingWidget)]);
    } else {
      current = Row(
        children: [
          if (leadingExpanded) Expanded(child: leadingWidget) else leadingWidget,
          widget.center,
          if (trailingExpanded) Expanded(child: trailingWidget) else trailingWidget,
        ],
      );
    }
    return current;
  }

  double calculateTextWidth(String text, double maxWidth) {
    if (text.isEmpty) return 0.0;
    TextPainter painter = TextPainter(
      locale: Localizations.localeOf(context),
      maxLines: 1,
      textDirection: TextDirection.ltr,
      text: TextSpan(text: text, style: widget.textStyle),
    );
    painter.layout(maxWidth: maxWidth);
    return painter.width;
  }
}
